package com.offcn.question.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.utils.PageUtils;
import com.offcn.utils.Query;

import com.offcn.question.dao.QuestionDao;
import com.offcn.question.entity.QuestionEntity;
import com.offcn.question.service.QuestionService;
import org.springframework.web.multipart.MultipartFile;

@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao, QuestionEntity> implements QuestionService {

    @Autowired
    private QuestionDao questionDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("id", key).or().like("title", key);
        }
        String type = (String) params.get("type");
        if (!StringUtils.isEmpty(type)) {
            queryWrapper.eq("type", type);
        }
        IPage<QuestionEntity> page = this.page(
                new Query<QuestionEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 导入数据
     *
     * @param file
     * @return file
     */
    @Override
    public Map<String, Object> importExcel(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        //获取上传文件名称
        String filename = file.getOriginalFilename();
        //判断文件名后缀 xls xlsx
        assert filename != null;
        if (!filename.matches("^.+\\.(?i)(xls)$") && !filename.matches("^.+\\.(?i)(xlsx)$")) {
            result.put("result", false);
            result.put("msg", "文件扩展名不正确，导入失败");
            result.put("num", 0);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //初始化创建工作簿对象
            Workbook workbook = WorkbookFactory.create(inputStream);
            //获取第一张工作表
            Sheet sheet = workbook.getSheetAt(0);
            //获取工作表里面有数据行数
            int rows = sheet.getPhysicalNumberOfRows();
            //循环表格行
            for (int i = 1; i < rows; i++) {
                Row row = sheet.getRow(i);
                QuestionEntity questionEntity = new QuestionEntity();
                questionEntity.setTitle(row.getCell(0).getStringCellValue());
                questionEntity.setAnswer(row.getCell(1).getStringCellValue());
                questionEntity.setLevel((int) row.getCell(2).getNumericCellValue());
                questionEntity.setDisplayOrder((int) row.getCell(3).getNumericCellValue());
                questionEntity.setSubTitle(row.getCell(4).getStringCellValue());
                questionEntity.setType((long) row.getCell(5).getNumericCellValue());
                questionEntity.setEnable((int) row.getCell(6).getNumericCellValue());
                this.save(questionEntity);
            }
            result.put("result", true);
            result.put("msg", "导入成功");
            result.put("num", rows - 1);
            System.out.println("导入成功总条数:" + (rows - 1));
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("msg", "文件导入失败，" + e.getMessage());
            result.put("num", 0);
        }
        return result;
    }

    /**
     * 导出数据
     *
     * @return file
     */
    @Override
    public Workbook exportExcel() {
        // 创建新的Excel 工作簿
        Workbook workbook = new HSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值 Sheet0
        // 创建工作表
        Sheet sheet = workbook.createSheet("题库");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("题目标题");
        row.createCell(1).setCellValue("题目解答");
        row.createCell(2).setCellValue("题目难度等级");
        row.createCell(3).setCellValue("排序");
        row.createCell(4).setCellValue("副标题");
        row.createCell(5).setCellValue("题目类型");
        row.createCell(6).setCellValue("是否显示");
        List<QuestionEntity> list = this.list();
        for (int i = 0; i < list.size(); i++) {
            Row row2 = sheet.createRow(i + 1);
            //创建表格
            row2.createCell(0).setCellValue(list.get(i).getTitle());
            row2.createCell(1).setCellValue(list.get(i).getAnswer());
            row2.createCell(2).setCellValue(list.get(i).getLevel());
            row2.createCell(3).setCellValue(list.get(i).getDisplayOrder());
            row2.createCell(4).setCellValue(list.get(i).getSubTitle());
            row2.createCell(5).setCellValue(list.get(i).getType());
            row2.createCell(6).setCellValue(list.get(i).getEnable());
        }
        return workbook;
    }

    /**
     * 题目类型统计表
     *
     * @return map
     */
    @Override
    public List<Map<String, Object>> countTypeQuestion() {
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<QuestionEntity>()
                .select("type,COUNT(TYPE) AS num").groupBy("type");
        return questionDao.selectMaps(queryWrapper);
    }

}